import { getUsableSelectedCouponList } from '@/dataTransfer/coupon.js';
import utils from '@/utils';
import YiCode from '@/components/yi-code'
import { debounce,debounceDelay } from '@/utils/helper';
import { RoundNum } from "@/utils/Tools";
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { View,Text,Image } from '@tarojs/components';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import { AtModal } from "taro-ui";
import classNames from 'classnames';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import AddressView from './AddressView';
import { DistributionWay, OrderType, StoreType } from './constant';
import DeliveryWay from './DeliveryWay';
import styles from './index.module.scss';
import OrderFailedDialog from './OrderFailedDialog';
import OrderPriceDetail from './OrderPriceDetail';
import OrgView from './OrgView';
import Summation from './Summation';
import request from '@/utils/request'
import './index.less'

const ConfirmOrder = ({
  dispatch,
  loading,
  buyNow,
  defaultAddress,
  cartShopSelected,
  cartShopProductReleaseIds,

  usableCouponList,
  usableCouponListPlat,

  giftCardSelected,
  eInvoiceSelected,
}) => {
  useShowLoading(loading);
  const { params: { merchantId, orgId, type, buyNow: inputBuyNow } = {} } = useRouter();
  // 不是立即购买, 就置空
  const [buyNowData] = useState(inputBuyNow === '1' ? { ...buyNow } : {});
  const isBuyNow = Object.keys(buyNowData).length > 0;

  // 门店类型 2：商城4：外卖
  const storeType = StoreType.shop;
  // 配送方式
  const [distributionWay, setDistributionWay] = useState(1);
  let distributionWayList = ['1']
  // 订单详情
  const [orderDetail, setOrderDetail] = useState({}); // 订单参数详情
  const { productCarConfirmOrgResponsesList = [] } = orderDetail;

  // 订单状态, 用于显示dialog
  const [orderStatus, setOrderStatus] = useState({ isOpened: false, code: '' });

  // 最后付款总计
  const [summation, setSummation] = useState({});
  // 地址信息
  const [addressInfo, setAddressInfo] = useState();
  const [curCard,setCurCard] = useState({})

  const showDialog = (data) => {
    setOrderStatus({ isOpened: true, ...data });
  };
  const [captcha,setCaptcha] = useState('')
  const [showModal,setShowModal] = useState(false)
  const [messageInfo,setMessageInfo] = useState('')

  // 清除 订单相关 选择
  const resetSelectData = () => {
    // 优惠券清空
    dispatch({ type: 'giftCard/resetOrderCouponListAll' });
    // 积分清空
    dispatch({ type: 'order/resetOrderPoint' });
    // 礼品卡清空
    dispatch({
      type: 'productCar/setGiftCardSelect',
      payload: [],
    });
  };

  // 获取收货地址
  useDidShow(() => {
    if (!addressInfo?.name) {
      dispatch({ type: 'giftCard/allAddressesModel' });
    }
  });

  // 更新 收货地址
  useEffect(()=>{
    _getAddress(defaultAddress)
    Taro.eventCenter.off('changeCard')
    Taro.eventCenter.on('changeCard', async (data)=>{
      if(data.curCard){
        setCurCard(data.curCard)
      }else{
        setCurCard({})
      }
    })
  }, []);
  useEffect(()=>{
    if(addressInfo?.id){
      _getAddress(addressInfo)
    }
  },[addressInfo])
  const _getAddress = values=>{
    const {
      id: addressId,
      contactName,
      address,
      mobile,
      houseNumber,
      city,
      cityCode,
      latitude,
      longitude,
    } = values;
    const addressStr = `${address || ''}${houseNumber || ''}`;

    const loginMobile = utils.getMobile();
    const data = {
      addressId,
      address: addressStr,

      city: city || '苏州',
      cityCode: cityCode || '0512',
      country: '',
      mobile: mobile || loginMobile,
      name: contactName,
      phone: '',
      postcode: '',
      province: '',
      latitude,
      longitude,

      address1: address,
      address2: houseNumber,
      contactName: contactName,
    }
    setAddressInfo(data);
    _getData(data)
  }
  const _getData = data=>{
    let payload = {
      // 立即购买数据
      productItemRequestList: isBuyNow ? [{ ...buyNowData }] : undefined,
      // 购物车ID
      idList: !isBuyNow ? cartShopSelected : undefined,

      distributionWay,
      ...data,
    };
    dispatch({
      type: 'order/getOrderConfirmInfo',
      payload,
      noToast: true,
    })
      .then((res) => {
        resetSelectData();
        setOrderDetail(res);
      })
      .catch((e) => {
        // 显示 dialog
        showDialog(e?.extra);
      })
  }
  // 获取店铺支持的配送方式
  // useEffect(() => {
  //   if (!storeType) {
  //     return;
  //   }
  //   let productReleaseIds = [];
  //   if (isBuyNow) {
  //     productReleaseIds = [buyNowData?.productReleaseId];
  //   } else {
  //     productReleaseIds = cartShopProductReleaseIds;
  //   }

  //   if (!productReleaseIds?.length) {
  //     Taro.navigateBack();
  //     return;
  //   }

  //   dispatch({
  //     type: 'order/getOrgDistributionWay',
  //     payload: {
  //       merchantId,
  //       orgId,
  //       storeType,
  //       productReleaseIds: productReleaseIds.join(','),
  //     },
  //   });
  // }, [storeType, cartShopProductReleaseIds, isBuyNow, buyNowData]);

  // 退出时清空
  useEffect(() => {
    Taro.setNavigationBarTitle({
      title:'确认订单'
    })
    return () => {
      resetSelectData();
      // 非团餐地址清空
      dispatch({
        type: 'productCar/setDefaultAddress',
        payload: {},
      });
      //清除已选发票抬头
      dispatch({
        type: 'productCar/setInvoiceSelected',
        payload: {},
      });

      // 清除配送方式
      dispatch({
        type: 'order/setOrgDistributionWay',
        payload: { distributionWayList: undefined },
      });
    };
  }, []);

  // 提交订单
  const handleSave = debounce(() => {
    // 判断收货地址
    if (!addressInfo?.contactName && distributionWay !== DistributionWay.selfHelp) {
      return Taro.showToast({
        mask: true,
        title: '请先选择收货地址',
        icon: 'none',
      });
    }

    const { selectedCouponList } = getUsableSelectedCouponList(usableCouponList);
    const { selectedCouponList: selectedCouponListPlat } = getUsableSelectedCouponList(
      usableCouponListPlat,
    );
    const selectedCouponListAll = [...selectedCouponList, ...selectedCouponListPlat];

    let data = {
      distributionWay,
      mobile: addressInfo.mobile,
      addressRequest: distributionWay === DistributionWay.selfHelp ? undefined : addressInfo,
      userSource: 'wechat',
      currency: '4217',
      titleId: eInvoiceSelected.id ?? '',
      totalPrice: parseFloat(summation?.submitTotalPrice).toFixed(2),
      giftCardIdList: giftCardSelected?.map((v) => v.id),
      customerRemark:summation.customerRemark,
      cinemaId: Taro.getStorageSync('merchantId'),
      couponList: selectedCouponListAll?.map((item) => {
        item.fineCouponId = item.couponId;
        item.publicType = 1;
        item.fineCouponType = item.type == 1 || item.type == 2 ? 1 : 2;
        return {
          ...item,
        };
      }),
      pointsList: summation?.selectedPoint?.chooseDeductionList?.length
        ? [
            {
              discountAmount: summation?.selectedPoint.choosePrice,
              usePoints: summation?.selectedPoint.choosePoint,
            },
          ]
        : [],
    };
    data = isBuyNow
      ? { ...data, productItemRequestList: [{ ...buyNowData }] }
      : { ...data, productCarRequest: cartShopSelected.map((v) => ({ productCarId: v })) };
    if(curCard.id){
      data.cardId = curCard.id
    }
    Taro.$post('/product/v1/product/product-car-order/createOrderV2',data).then(async res=>{
      if(res.code == '1'){
        const e = res.content
        // 清除礼品卡选择
        await dispatch({ type: 'productCar/setGiftCardSelect', payload: [] });
        await dispatch({ type: 'productCar/getCartList' });
        if(e.needPay == '1'){
          Taro.redirectTo({ url: `/pages/fineEngine/payment?id=${e.orderIdList[0]}` });
        }else{
          Taro.redirectTo({
            url:`/orderSubPack/pay-status/index?id=${e.orderIdList[0]}`
          })
        }
      }else{
        Taro.$toast(res.message)
      }
    })
  }, 2000);

  return (
    <View className={styles.ConfirmOrder}>
      <View
        className="cards"
        style={{
          height: utils.getCalcHeight(
            {},
            // 底部提交订单
            98,
            // 手机自带菜单
            Taro.$bottomHight ? 68 : 0,
          ),
        }}
      >
        <OrderFailedDialog status={orderStatus} />
        <DeliveryWay
          {...{
            distributionWayList,
            value: distributionWay,
            onChange: setDistributionWay,
          }}
        />

        <AddressView
          className="card-wrap"
          {...{
            distributionWay,
            distributionWayList,

            merchantId,
            orgId,

            value: addressInfo,
            onChange: e=>{
              setAddressInfo(e)
            },
          }}
        />

        {productCarConfirmOrgResponsesList?.map((orgInfo,index) => {
          return <OrgView className="card-wrap" key={index} orgInfo={orgInfo} />;
        })}

        <OrderPriceDetail className="card-wrap" orderDetail={orderDetail} onChange={setSummation} />

        <OrgView
          className="card-wrap"
          orgInfo={{
            disabled: true,
            productCarConfirmInfoList: orderDetail?.distributionWayLimitList ?? [],
          }}
        />
        
        <View className='confirm-order-part-3'>
          <View className='row-1'>支付方式</View>
          <View className='item'>
            <View className='c-1'>电影卡支付</View>
            <View className='c-2' onClick={()=>{
              Taro.navigateTo({
                url:`/mainPages/select-card/index?cardId=${curCard.id}&price=${summation?.submitTotalPrice}&type=shops`
              })
            }}>
              {curCard?.id?<Text>{curCard.cardName}</Text>:<Text className='i-1'>未使用</Text>}
              <Image className='i-2' src={require('@/images/ticket/right.png')}></Image>
            </View>
          </View>
          {curCard?.id?<View className="item-p">
            <View>余额：¥{curCard.amount}</View>
            <View>消费余额：¥{curCard.amount - summation?.submitTotalPrice>0?RoundNum(curCard.amount - summation?.submitTotalPrice):0}</View>
          </View>:null}
          <View className='item'>
            <View className='c-1'>{process.env.TARO_ENV == 'tt'?'抖音支付':'微信支付'}</View>
            <View className='c-2'>
              <Image className='i-2' src={require('@/images/mine/radio-on.svg')}></Image>
            </View>
          </View>
        </View>
      </View>
      <Summation
        className={classNames('bottom-summation', { bottomHeight: Taro.$bottomHight })}
        summation={{...summation,
          submitTotalPrice:curCard?.id?
          summation.submitTotalPrice - curCard.amount>0?summation.submitTotalPrice - curCard.amount:0:
          summation.submitTotalPrice
        }}
        handleSave={()=>{
          if(curCard?.id){
            setShowModal(true)
            return;
          }
          handleSave()
        }}
      />
      <AtModal className="confirm-order-modal" isOpened={showModal} onClose={()=>{setShowModal(false)}}>
        {showModal?<>
        <View className="modal-header">
          <View className='at-icon at-icon-close' onClick={()=>{setShowModal(false)}}></View>
          <View className="header-h2">验证卡密码</View>
          <View></View>
        </View>
        <View className="modal-main">
          <View className="main-span" style={{marginBottom:'24px'}}>为了保证你的账号安全，请输入您的会员卡密码后进行下一步操作。</View>
          <YiCode isFocus={showModal} inputType='password' value={captcha} onConfirm={(code) => {
            setCaptcha(code)
          }} />
          {messageInfo?<View className="main-info"><Text style={{marginRight:'4px'}} className='at-icon at-icon-alert-circle'></Text>{messageInfo}</View>:null}
        </View>
        <View className="modal-footer">
          <View className="footer-go" onClick={()=>{
            if(captcha.trim()){
              const data = {
                cardId: curCard.id,
                password: captcha,
                type:curCard.isDxCard
              }
              Taro.showLoading({title:"加载中..."})
              Taro.$post('/cinema-app/api/card/checkPassword',data,'1').then(res=>{
                if(res.code == '1' && res.content){
                  handleSave()
                }else{
                  setMessageInfo('密码错误')
                  setCaptcha('')
                }
              })
            }
          }}>提交订单</View>
        </View>
        </>:null}
      </AtModal>
    </View>
  );
};

export default connect(({ productCar, loading, giftCard, order }) => ({
  loading,

  distributionWayList: order.orgDistributionWay,

  buyNow: productCar.buyNow,
  defaultAddress: productCar.defaultAddress,
  cartShopSelected: productCar.cartShopSelected,
  cartShopProductReleaseIds: productCar.cartShopProductReleaseIds,

  usableCouponList: giftCard.usableCouponList,
  usableCouponListPlat: giftCard.usableCouponListPlat,

  giftCardSelected: productCar.giftCardSelected,

  eInvoiceSelected: productCar.eInvoiceSelected,
}))(ConfirmOrder);
